package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.pojo.Member;
import com.atguigu.service.MemberService;
import com.atguigu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * @program: meinian_parent
 * @author: Mr.Zhuo
 * @create: 2022-02-18 19:55
 **/
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    @PostMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        // 然后获取redis中的验证码
        String validateCodeNo = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (!(validateCode != null && validateCode.equals(validateCode))) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        // 然后判断当前是否为注册用户，如果不是快速注册
        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());

            memberService.add(member);
        }

        // 登陆成功保存到cookie中
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        // 设置cookie被访问的路径
        cookie.setPath("/");
        // 设置cookie有效时长 (30天)
        cookie.setMaxAge(60 * 60 * 24 * 30);

        // 然后保存
        response.addCookie(cookie);

        // 最后返回所有值
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }


}
